# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import csv
import os

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class FmPipeline:
    def process_item(self, item, spider):
        if spider.name == 'qingting':
            download_path = os.getcwd() + os.sep + 'download'
            if not os.path.exists(download_path):
                os.mkdir(download_path)
            type = item.get('type')
            if type == 'img':
                filename = item.get('filename')
                img = item.get('img')
                print("----------------save img------------------")
                with open(download_path + os.path.sep+filename,'wb') as f:
                    f.write(img)
                    print('保存%s成功' % filename)
                return

            elif type == 'info':
                print("----------------save info------------------")
                with open(download_path + os.sep+'蜻蜓FM.csv','a',encoding='utf-8') as f:
                    # 创建一个csv的DictWriter对象，这样才能够将写入csv格式数据到这个文件
                    f_csv = csv.DictWriter(f, ['id', 'img_src', 'title', 'desc', 'play_number'])
                    # 写入多行行（当做数据）
                    f_csv.writerows([item])
                    print("保存信息到CSV....ok")
